Page({
  data: {
    tagList: ['要闻', '音乐', '科技', '经济', '军事'],
    tagValueList: [1, 2, 3, 4, 5],
    selectedTag: 1,
    newsList: []
  },
 
  switchTab: function (e) {
    const tagId = parseInt(e.currentTarget.dataset.tag);
    this.setData({
      selectedTag: tagId
    });
    this.getNewsByTag(tagId);
  },
  shouldPlaceholder(title) {
    return title.length > 20;
  },
  // 根据标签请求新闻
  getNewsByTag: function (tagId) {
    const baseUrl = 'http://39.104.24.231:8082';
    const url = `${baseUrl}/news/tag/${tagId}`;
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.status === 200) {
          this.setData({
            newsList: res.data.data
          });
          wx.showToast({
            title: '新闻获取成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '新闻获取失败: ' + res.data.message,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '请求失败: ' + err.errMsg,
          icon: 'none'
        });
      }
    });
  },

  // 页面加载时默认请求要闻新闻
  onLoad: function () {
    this.getNewsByTag(this.data.selectedTag);
  },

  // 跳转到新闻详情页
  goDetail: function (e) {
    const newsId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail2/detail2?id=${newsId}`
    });
  }
});